﻿using Daemon.Common.Const;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Model;
using Daemon.Repository.Contract;
using Daemon.Repository.EF.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Daemon.Repository.EF
{
	public class ProjectInfoRepository : Repository<ProjectInfo>, IProjectInfoRepository
	{
		private readonly IDatabaseConfigRepository _databaseConfigRepository;

		protected override Expression<Func<ProjectInfo, int>> PrimaryKeyExpression => r => r.Id;

		public ProjectInfoRepository(ApiDBContent context
			, IDatabaseConfigRepository databaseConfigRepository) : base(context)
		{
			_databaseConfigRepository = databaseConfigRepository;
		}

		protected override IEnumerable<ProjectInfo> IncludeRelationships(IEnumerable<ProjectInfo> entities, ApiDBContent db)
		{
			SetDatabaseConfig(entities);

			return entities;
		}

		protected override void SaveRelationships(ProjectInfo entity, ProjectInfo entityWithRelationships, ApiDBContent db, short entityORMType)
		{
			SaveDatabaseConfig(entityWithRelationships, entityORMType);
		}

		private void SetDatabaseConfig(IEnumerable<ProjectInfo> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, ProjectInfoRelationshipEnum.DatabaseConfig))
			{
				return;
			}

			var ids = entities.Select(r => r.Id).ToList();
			var databaseConfigDic = Context.DatabaseConfig.Where(r => ids.Contains(r.ProjectId)).ToDictionary(r => r.ProjectId, r => r);
			foreach (var entity in entities)
			{
				if (databaseConfigDic.TryGetValue(entity.Id, out DatabaseConfig config))
				{
					entity.DatabaseConfig = config;
				}
			}
		}

		private void SaveDatabaseConfig(ProjectInfo entityWithRelationships, short entityORMType)
		{
			if (entityORMType == EntityORMType.UPDATE_TYPE_NUMBER)
			{
				entityWithRelationships.DatabaseConfig.ProjectId = entityWithRelationships.Id;
				_databaseConfigRepository.AddByDBContext(entityWithRelationships.DatabaseConfig);
			}
			else
			{
				_databaseConfigRepository.UpdateByDBContext(entityWithRelationships.DatabaseConfig);
			}
		}
	}
}
